package com.captcha.demos.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.captcha.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class Captcha {

    private  static final long VALUE_TIME=2*60*1000L;

    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/getCaptcha")
    // 请求映射，当访问/getCaptcha时，调用该方法
    public void getCaptcha(HttpServletResponse response,HttpSession session){
        // 设置响应内容类型为图片
        response.setContentType("image/jpeg");
        // 设置响应字符编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        try {
            // 创建一个线型验证码
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            // 获取验证码
            String code= lineCaptcha.getCode();
            System.out.println(code);
            // 将验证码存入session
            session.setAttribute(captchaProperties.getSession().getCode(),code);
            // 将验证码生成时间存入session
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());
            // 将验证码写入响应输出流
            lineCaptcha.write(response.getOutputStream());
        } catch (IOException e) {
            // 抛出运行时异常
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(HttpSession session,String captchaCode){
        // 判断captchaCode是否为空
        if(!StringUtils.hasLength(captchaCode)){
            return false;
        }
        // 获取session中的验证码
        String code=(String) session.getAttribute(captchaProperties.getSession().getCode());
        // 获取session中的验证码生成时间
        Date date=(Date) session.getAttribute(captchaProperties.getSession().getDate());
        // 判断验证码是否正确，且验证码生成时间是否在有效期内
        if(code.equals(captchaCode)&&date!=null&&(System.currentTimeMillis()- date.getTime()<VALUE_TIME)){
            return true;
        }
        return false;
    }




}
